package org.lee.springcloud.consul.controllers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 调用服务
 *
 * @author jackielee
 * @version 1.0
 * @description CallHelloController
 * @date 2021/3/15
 */
@RestController
public class CallHelloController {

  @Autowired private LoadBalancerClient loadBalancer;

  /**
   * 调用 service-producer服务
   * @param path 服务下的路径
   * @return
   */
  @GetMapping("/call")
  public String call(@RequestParam(name = "path", defaultValue = "/hello") String path) {
    ServiceInstance serviceInstance = loadBalancer.choose("service-producer");
    System.out.println("服务地址：" + serviceInstance.getUri());
    System.out.println("服务名称：" + serviceInstance.getServiceId());
    String callResult = new RestTemplate().getForObject(serviceInstance.getUri()+path, String.class);
    System.out.println(callResult);
    return callResult;
  }
}
